package com.rh.bmw4s.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;
import com.rh.bmw4s.R;
import com.rh.bmw4s.adapter.ImagePickerTwoAdapter;
import com.rh.bmw4s.bean.SuqiuImgsBean;
import com.rh.bmw4s.bean.SuqiuOtherBean;
import com.rh.bmw4s.comm.ConfigValue;
import com.rh.bmw4s.comm.Constant;
import com.rh.bmw4s.utills.CheckUtil;
import com.rh.bmw4s.utills.DialogUtils;
import com.rh.bmw4s.utills.LogUtils;
import com.rh.bmw4s.utills.SPUtils;
import com.rh.bmw4s.utills.ToastUtils;
import com.rh.bmw4s.view.PicassoImageLoader;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 投诉建议界面
 */
public class ComplainActivity extends BaseActivity implements ImagePickerTwoAdapter.OnRecyclerViewItemClickListener {

    @BindView(R.id.title_left_one_btn)
    ImageView titleLeftOneBtn;
    @BindView(R.id.tv_middle_title)
    TextView tvMiddleTitle;
    @BindView(R.id.aftersale_edit)
    EditText editProblem;
    @BindView(R.id.aftersale_recyclerView)
    RecyclerView recyclervVew;
    @BindView(R.id.aftersale_btn)
    TextView btnCommit;
    @BindView(R.id.edit_tousu_phone)
    EditText editPhone;

    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
    private ImagePickerTwoAdapter adapter;
    private ArrayList<ImageItem> selImageList; //当前选择的所有图片
    private int maxImgCount = 4;               //允许选择图片最大数
    private String userId;
    private String goodsID;
    private Gson gson;
    private List<String> datas = new ArrayList<>();
    private boolean isSelectImg = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_complain);
        ButterKnife.bind(this);
        gson = new Gson();

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        initView();
        initRecy();
    }

    private void initRecy() {
        selImageList = new ArrayList<>();
        adapter = new ImagePickerTwoAdapter(this, selImageList, maxImgCount);
        adapter.setOnItemClickListener(this);
        recyclervVew.setLayoutManager(new GridLayoutManager(this, 4));
        recyclervVew.setHasFixedSize(true);
        recyclervVew.setAdapter(adapter);
    }

    private void initView() {
        titleLeftOneBtn.setVisibility(View.VISIBLE);
        tvMiddleTitle.setText("投诉建议");

        editProblem.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (MotionEvent.ACTION_DOWN == event.getAction()) {
                    editProblem.setCursorVisible(true);
                    //KeyboardUtils.showSoftInput(ComplainActivity.this);
                }
                return false;
            }
        });

        /**监听edittext换行*/
        editProblem.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //点击换行时，如果已经10行了，就使edittext禁用换行
                int lineCount = editProblem.getLineCount();
                if (lineCount >= 10) {
                    editProblem.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                        @Override
                        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                            ToastUtils.toastForShort(ComplainActivity.this, "最多输入10行");
                            return (event.getKeyCode() == KeyEvent.KEYCODE_ENTER);
                        }
                    });
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }


    @OnClick({R.id.title_left_one_btn, R.id.aftersale_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_left_one_btn:
                finish();
                break;
            case R.id.aftersale_btn:
                //提交投诉建议
                if (checkContent()) {
                    commitOthers();
                }
                break;
        }
    }

    /**
     * 提交图片
     */
    private void commitImgs() {
        //先上传图片，图片上传成功在上传其他
        DialogUtils.showProgressDlg(ComplainActivity.this, "正在提交图片......");
        PostRequest<String> request = OkGo.<String>post(Constant.UpLoadMulitImg).tag(ComplainActivity.this);
        switch (selImageList.size()) {
            case 0:
                request.params("img0", "");
                request.params("img1", "");
                request.params("img2", "");
                request.params("img3", "");
                break;
            case 1:
                request.params("img0", new File(selImageList.get(0).path));
                request.params("img1", "");
                request.params("img2", "");
                request.params("img3", "");
                break;
            case 2:
                request.params("img0", new File(selImageList.get(0).path));
                request.params("img1", new File(selImageList.get(1).path));
                request.params("img2", "");
                request.params("img3", "");
                break;
            case 3:
                request.params("img0", new File(selImageList.get(0).path));
                request.params("img1", new File(selImageList.get(1).path));
                request.params("img2", new File(selImageList.get(2).path));
                request.params("img3", "");
                break;
            case 4:
                request.params("img0", new File(selImageList.get(0).path));
                request.params("img1", new File(selImageList.get(1).path));
                request.params("img2", new File(selImageList.get(2).path));
                request.params("img3", new File(selImageList.get(3).path));
                break;
        }
        request.execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                LogUtils.d("fff", response.body().toString());
                SuqiuImgsBean imgsBean = gson.fromJson(response.body().toString(), SuqiuImgsBean.class);
                ToastUtils.toastForShort(ComplainActivity.this, imgsBean.getMsg());
                if (imgsBean.getStatus() == Constant.SUCESS) {
                    DialogUtils.stopProgressDlg();
                    datas = imgsBean.getDatas();
                    isSelectImg = true;
                } else {
                    //图片上传失败，直接结束
                    DialogUtils.stopProgressDlg();
                    isSelectImg = false;
                }

            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                ToastUtils.toastForShort(ComplainActivity.this, "提交失败");
                DialogUtils.stopProgressDlg();
                isSelectImg = false;
            }
        });
    }

    /**
     * 提交其他类型
     */
    private void commitOthers() {
        DialogUtils.showProgressDlg(ComplainActivity.this, "正在提交......");

        StringBuilder strBuilder = new StringBuilder();
        if (isSelectImg) {
            for (int i = 0; i < 4; i++) {
                if (TextUtils.isEmpty(datas.get(i))) {
                    strBuilder.append("");
                    break;
                } else {
                    if (i == 0) {
                        strBuilder.append(datas.get(i));
                    } else {
                        strBuilder.append("," + datas.get(i));
                    }
                }
            }
        } else {
            strBuilder.append("");
        }

        int anInt = SPUtils.getInstance().getInt(ConfigValue.userId);
        String strPhone = editPhone.getText().toString();
        String strProblem = editProblem.getText().toString();
        LogUtils.d("aaa", strBuilder.toString());

        OkGo.<String>post(Constant.UpLoadComplain)
                .tag(ComplainActivity.this)
                .params("mem_id", anInt)
                .params("tel", strPhone)
                .params("content", strProblem)
                .params("logo", strBuilder.toString())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        SuqiuOtherBean otherBean = gson.fromJson(response.body().toString(), SuqiuOtherBean.class);
                        ToastUtils.toastForShort(ComplainActivity.this, otherBean.getMsg());
                        if (otherBean.getStatus() == Constant.SUCESS) {
                            finish();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        DialogUtils.stopProgressDlg();
                        ToastUtils.toastForShort(ComplainActivity.this, "提交失败");
                    }
                });

    }

    private boolean checkContent() {
        String strPhone = editPhone.getText().toString();
        String strProlem = editProblem.getText().toString().trim();
        if (!CheckUtil.isMobileNO(strPhone)) {
            ToastUtils.toastForShort(ComplainActivity.this, "手机号码不正确");
            return false;
        }
        if (TextUtils.isEmpty(strProlem)) {
            ToastUtils.toastForShort(ComplainActivity.this, "诉求内容不能为空");
            return false;
        }
        return true;
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                //打开选择,本次允许选择的数量
                ImagePicker imagePicker = ImagePicker.getInstance();
                imagePicker.setImageLoader(new PicassoImageLoader());   //设置图片加载器
                imagePicker.setMultiMode(true);
                imagePicker.setSelectLimit(maxImgCount - selImageList.size());
                imagePicker.setCrop(false);        //允许裁剪（单选才有效）
                imagePicker.setSaveRectangle(true); //是否按矩形区域保存
                imagePicker.setFocusWidth(600);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
                imagePicker.setFocusHeight(600);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
                imagePicker.setOutPutX(300);//保存文件的宽度。单位像素
                imagePicker.setOutPutY(300);//保存文件的高度。单位像素
                Intent intent1 = new Intent(ComplainActivity.this, ImageGridActivity.class);

                startActivityForResult(intent1, REQUEST_CODE_SELECT);
                break;
            default:
                //打开预览
                Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                break;
        }
    }

    ArrayList<ImageItem> images = null;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);

                    commitImgs();
                }
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    selImageList.clear();
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                }
            }
        }

    }


}
